import motor
import asyncio
import json
import os
from datetime import datetime
from motor.motor_asyncio import AsyncIOMotorClient

__URL = os.getenv("MONGO_URL")
session = AsyncIOMotorClient(__URL)
db = session.UserBotTelegram
path = "CryptoFarm/local.json"


class DB:
    async def get_config():
        api_id = await db.config.find_one({"_id": "api_id"})
        api_hash = await db.config.find_one({"_id": "api_hash"})
        return api_id.pop("api_id"), api_hash.pop("api_hash")

    async def save_channel(String):
        return db.crypto.insert_one({"String": String, "type": "channel"})

    async def delete_channel(String):
        return db.crypto.delete_one({"String": String, "type": "channel"})

    async def get_channels():
        channels = []
        async for channel in db.crypto.find({"type": "channel"}):
            channels.append(channel)
        return channels


class LocalDB_JSON:
    def __init__(self):
        if os.path.exists(path):
            pass
        else:
            with open(path, "w") as f:
                json.dump(
                    {
                        "ROOT": {
                            "created_on": datetime.now().strftime("%Y:%m:%d %H:%M"),
                            "changed": datetime.now().strftime("%Y:%m:%d %H:%M"),
                            "NAMED_BOT": "LTC",
                        }
                    },
                    f,
                    indent=4,
                    sort_keys=True,
                )

    def create_user(self, api_id, api_hash):
        with open(path, "r") as f:
            data = json.load(f)
        try:
            data["USERS"]
        except:
            data["USERS"] = []
        user = {}
        user["api_id"] = api_id
        user["api_hash"] = api_hash
        user["number_phone"] = 0
        if data["USERS"][-1]["file_session"] == "session.session":
            user["file_session"] = "session_1.session"
        else:
            session = data["USERS"][-1]["file_session"]
            number_session = session.split("_")[-1]
            user["file_session"] = f"session_{str(int(number_session) + 1)}.session"
        data["USERS"].append(user)
        with open(path, "w") as f:
            json.dump(data, f, indent=4, sort_keys=True)

    def get_user(self, idx=None):
        if not idx:
            idx = 0

        with open(path, "r") as f:
            data = json.load(f)
        if idx + 1 > len(data["USERS"]):
            return None
        return data["USERS"][idx]

    def get_users(self):
        with open(path, "r") as f:
            data = json.load(f)
        return data["USERS"]

    def update_user(self, number_phone, update_field, update_value):
        with open(path, "r") as f:
            data = json.load(f)
        count = 0
        for i in data["USERS"]:
            count += 1
            if i["number_phone"] == number_phone:
                update_idx = count
            else:
                continue
        if not update_idx:
            return False
        data["USERS"][update_idx][update_field] = update_value
        data["ROOT"]["changed"] = datetime.now().strftime("%Y:%m:%d %H:%M")
        with open(path, "w") as f:
            json.dump(data, f, indent=4, sort_keys=True)

    def get_named_bot(self):
        with open(path, "r") as f:
            data = json.load(f)
        return data["ROOT"]["NAMED_BOT"]


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(DB.get_channels())
